package com.oracle.application.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author bug制造者
 * @ClassName SendEmailService.java
 * @createTime 2021年07月09日 09:27:00
 * @Description
 */
@Service
public class SendEmailService {
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String sender;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 发送邮件
     * @param targetMail
     */
    public void sendEmailCode(String targetMail){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(sender);
        simpleMailMessage.setTo(targetMail); //自己给自己发送邮件
        simpleMailMessage.setSubject("主题：注册验证码");
        String code = createCode();
        redisTemplate.boundValueOps("member:register:"+targetMail).set(code, 1, TimeUnit.MINUTES);
        simpleMailMessage.setText(code);
        mailSender.send(simpleMailMessage);
    }

    /**
     * 生成验证码
     * @return
     */
    public String createCode(){
        String randomCode=Math.random()*1000000+"";
        String code=randomCode.substring(0, randomCode.indexOf("."));
        return code;
    }
}
